package com.rankeiot.platform.service;

import com.rankeiot.core.data.MenuItem;
import com.rankeiot.core.util.CollectionUtil;
import com.rankeiot.core.util.StringUtil;
import com.rankeiot.core.Current;
import com.rankeiot.core.MenuManager;
import com.rankeiot.core.data.UserInfo;
import com.rankeiot.platform.domain.Role;
import com.rankeiot.platform.util.PasswordUtil;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Component
@RequiredArgsConstructor
public class UserService  {

    final RoleService roleService;

    final SqlToyLazyDao dao;

    @Autowired(required = false)
    IMemberLoader memberLoader;
    @PostConstruct
    public void init() {
        Current.setUserLoader((userType, userName) -> {
            if (Current.TYPE_MEMBER == userType) {
                return loadMember(userName, null);
            } else {
                return loadUserInfo(userName, null);
            }
        });
    }

    public UserInfo loadMember(String username, String password) {
        UserInfo userInfo = new UserInfo();
        if(memberLoader!=null){
            userInfo = memberLoader.loadMember(username,password);
        }else{
            userInfo.setUsername(username);
            userInfo.setPassword(password);
            userInfo = dao.loadBySql("member_login_info", userInfo);
            if(userInfo!=null){
                List<MenuItem> menu = (List<MenuItem>) MenuManager.getAllMemberMenu();
                userInfo.setMenu(menu);
            }
        }

        if (userInfo != null) {
            userInfo.setUserType(Current.TYPE_MEMBER);
            userInfo.setSuper(false);
        }
        return userInfo;
    }

    public UserInfo loadUserInfo(String username, String password) {
        // UserInfo info= mapper.findUserInfo(username,password);
        // @Sql("select * from t_user where username=:username #[and password=md5(concat(username,'$',:password))]")
        UserInfo query = new UserInfo();
        query.setUsername(username);
        // query.setPassword(password);
        UserInfo info = dao.loadBySql("select a.id,a.username,a.name,a.password,a.user_type,a.branch_sn,a.props,b.name branchName,b.id branchId,a.avatar,a.gender from t_user a left join t_branch b on a.branch_sn=b.sn where a.username=:username and a.enable=true and (b.enable=1 or b.enable is null) #[and password=md5(concat(username,'$',:password))]", query);
        if (info != null) {
            if (StringUtil.isNotEmpty(password)) {
                if (!Objects.equals(info.getPassword(), PasswordUtil.encodePassword(password,username))) {
                    return null;
                }
            }
            if ("admin".equals(username)) {
                //超级管理员权限，有全部菜单
                info.setMenu(MenuManager.getAllMenu(new HashSet<>(), true));
                info.setUserType(Current.TYPE_USER);
                info.setSuper(true);
                info.setPermissions(MenuManager.allStrPermission());
                info.setRoles(roleService.getAllRole());
                info.setScopes(CollectionUtil.asMap("admin","1"));
            } else {
                Set<String> permissions = roleService.getPermissionOfUser(username);
                info.setPermissions(permissions);
                info.setSuper(false);
                info.setUserType(Current.TYPE_USER);
                info.setMenu(MenuManager.getAllMenu(permissions, false));
                //  roleService.getRoleOfUser()
                List<Role> roles = roleService.getRoleOfUser(info.getUsername());
                info.setRoles(CollectionUtil.mapToSet(roles, Role::getSn));
                info.setScopes(CollectionUtil.toMap(roles, Role::getSn,Role::getScope));
            }

        }
        return info;
    }
}
